package com.zust.ysc012.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

import static com.zust.ysc012.dao.PublicDao.nowUser;
import static com.zust.ysc012.service.EnterService.*;

@WebServlet(urlPatterns = "/logInServlet")
public class LogInServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        HttpSession session = req.getSession(true);
        String name;
        int i = -1;
        try {
            i = getSign(account);
            if (i == -1) {
                //记得补充
                System.out.println("账号错误");
            } else {
                if (isCorrect(account, password, i)) {
                    name = getUserName(account);
                    session.setAttribute("sign", i);
                    session.setAttribute("account", account);
                    session.setAttribute("username", name);
                    nowUser(account);
                    req.getRequestDispatcher("/WEB-INF/notice.jsp").forward(req,resp);
                } else {
                    //记得扩充
                    req.getRequestDispatcher("index.jsp").forward(req,resp);
                }
            }
        }
        catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
